package com.tange.ai.iot.client.gnssa.play.multi

import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityDevicePlaybackThreeChannelBinding
import com.tange.base.toolkit.DateUtil
import com.tange.base.toolkit.Tips
import com.tange.base.toolkit.gone
import com.tange.base.toolkit.onClicked
import com.tange.base.toolkit.ui
import com.tange.base.toolkit.visible
import com.tange.core.device.facade.DeviceFacade
import com.tange.core.device.facade.Status
import com.tange.core.media.render.DeviceMediaRender
import com.tange.core.media.source.impl.local.DeviceStorageMediaSource
import com.tange.core.media.source.impl.local.DeviceStoragePlayback
import com.tg.appcommon.android.TGLog
import java.io.File

/**
 * 多视频通道的设备“本地回看”页面展示
 *
 * 此处 演示 2 个通道。
 *
 * 如有更多通道的需求，比如3、4、5、6 个，自行参考处理即可。
 *
 * 注意：仅演示视频播放，其余截屏等功能参考 DevicePlaybackActivity
 */
class ThreeChannelDevicePlaybackActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "ThreeChannelDevicePlaybackActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, ThreeChannelDevicePlaybackActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private var albumPath = Environment.getExternalStorageDirectory()
        .toString() + File.separator + Environment.DIRECTORY_DCIM

    private lateinit var deviceId: String

    private lateinit var binding: ActivityDevicePlaybackThreeChannelBinding

    private lateinit var deviceFacade: DeviceFacade
    private lateinit var deviceStorageMediaSource: DeviceStorageMediaSource

    // 视频通道-1 的渲染器：
    private lateinit var deviceMediaRender_1: DeviceMediaRender

    // 视频通道-2 的渲染器：
    private lateinit var deviceMediaRender_2: DeviceMediaRender

    // 视频通道-3 的渲染器：
    private lateinit var deviceMediaRender_3: DeviceMediaRender

    private var isLandscape = false
    private var rendered = false

    private val playbackIndexList = ArrayList<DeviceStoragePlayback.Index>()
    private var indexRequested = false

    private lateinit var listAdapter: ListAdapter

    private var speedPlayEnabled = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDevicePlaybackThreeChannelBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            com.tange.ai.iot.client.gnssa.utils.Utils.setDarkStatusBar(this@ThreeChannelDevicePlaybackActivity, Color.TRANSPARENT)
            listAdapter = ListAdapter()
            list.layoutManager = LinearLayoutManager(this@ThreeChannelDevicePlaybackActivity, LinearLayoutManager.VERTICAL, false)
            list.adapter = listAdapter
            name.text = "本地录像"
        }

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)!!

        // 创建设备交互模块
        configureConnection()

        // 创建 存储卡回放 媒体数据源
        configureMediaSource()

        // 创建 视频通道-1 的播放器
        configureVideoChannel_1()

        // 创建 视频通道-2 的播放器
        configureVideoChannel_2()

        // 创建 视频通道-3 的播放器
        configureVideoChannel_3()

        binding.loading.visible()
        binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_off_24))
        binding.audio.onClicked { switchAudio() }
        binding.back.onClicked { finish() }
        binding.connect.onClicked { deviceStorageMediaSource.enableVideoProduce(true) }
    }

    private fun configureVideoChannel_2() {
        deviceMediaRender_2 = DeviceMediaRender(this, deviceStorageMediaSource).apply {

            videoFrameFilter = DeviceMediaRender.MediaFrameFilterByCameraIndex(1)

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer2, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                TGLog.i(TAG, "[first-rendered] ")
                rendered = true
                binding.connect.gone()
                binding.loading.gone()
            }

            enableAudio(false)
        }
    }

    private fun configureVideoChannel_3() {
        deviceMediaRender_3 = DeviceMediaRender(this, deviceStorageMediaSource).apply {

            videoFrameFilter = DeviceMediaRender.MediaFrameFilterByCameraIndex(2)

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer3, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                TGLog.i(TAG, "[first-rendered] ")
                rendered = true
                binding.connect.gone()
                binding.loading.gone()
            }

            enableAudio(false)
        }
    }

    private fun configureVideoChannel_1() {
        deviceMediaRender_1 = DeviceMediaRender(this, deviceStorageMediaSource).apply {

            videoFrameFilter = DeviceMediaRender.MediaFrameFilterByCameraIndex(0)

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer1, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                TGLog.i(TAG, "[first-rendered] ")
                rendered = true
                binding.connect.gone()
                binding.loading.gone()
            }
        }

        deviceMediaRender_1.onTimestampUpdate = Consumer {
            binding.playTimestamp.post {
                binding.playTimestamp.text = DateUtil.getStrToTime(it)
            }
        }
    }

    private fun configureMediaSource() {
        deviceStorageMediaSource = DeviceStorageMediaSource(deviceFacade).apply {

            onReceiveNextPart = Consumer {
                TGLog.i(TAG, "开始播放：${DateUtil.getStrToTime(it)}")
            }

            observeVideoFrame {

                TGLog.i(TAG, "[configureMediaSourcessss] ------ ${it.data.subType}")
            }

        }
    }

    private fun configureConnection() {
        deviceFacade = DeviceFacade(deviceId).apply {

            // 监听连接状态变化
            observeConnectStatus {
                TGLog.i(TAG, "[connect-status] ${it.status}")
                ui {
                    if (it.status != Status.SUCCESS) {
                        if (it.status == Status.FAILED) {
                            binding.loading.gone()
                            binding.connect.visible()
                            binding.connect.text = "重试"
                            Tips.show("连接失败：$it")
                        } else {
                            binding.loading.visible()
                        }
                    } else {
                        queryRecord()

                        binding.connect.gone()
                        if (rendered) {
                            binding.loading.gone()
                        }
                    }
                }
            }
        }
    }

    private fun queryRecord() {
        if (!indexRequested) {

            binding.root.postDelayed({
                DeviceStoragePlayback(deviceFacade).query(DateUtil.getTodayDate()) {
                    ui {
                        binding.loading.gone()
                        if (it.success) {
                            it.data?.let { listAdapter.refresh(it) }
                            Tips.show("点击下方列表项")
                        } else {
                            if (DeviceStoragePlayback.ERROR_NO_RECORD == it.code) {
                                binding.emptyView.visible()
                            } else {
                                binding.emptyView.visible()
                                binding.emptyView.text = "错误：${it.code}, ${it.message}"
                            }
                        }
                    }
                }
            }, 0)


            indexRequested = true
        }
    }

    override fun onResume() {
        super.onResume()
        TGLog.i(TAG, "[onResume] ")
        deviceStorageMediaSource.enableVideoProduce(true)
    }

    override fun onPause() {
        super.onPause()
        TGLog.i(TAG, "[onPause] ")
        deviceStorageMediaSource.enableVideoProduce(false)
        deviceStorageMediaSource.enableAudioProduce(false)
        binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_off_24))
    }

    private fun createCenterLayoutParams() = FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.MATCH_PARENT,
        FrameLayout.LayoutParams.MATCH_PARENT
    ).apply { gravity = Gravity.CENTER }

    private fun switchAudio() {
        if (deviceStorageMediaSource.isAudioProduceEnabled()) {
            binding.audio.setImageDrawable(
                ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_off_24)
            )
            deviceStorageMediaSource.enableAudioProduce(false)
            deviceMediaRender_1.enableAudioRender(false)
        } else {
            binding.audio.setImageDrawable(
                ContextCompat.getDrawable(
                    this,
                    R.drawable.ic_baseline_volume_on_24
                )
            )
            deviceStorageMediaSource.enableAudioProduce(true)
            deviceMediaRender_1.enableAudioRender(true)
        }
    }

    private fun switchFullScreen() {
        if (isLandscape) {
            binding.bottomLayout.visibility = View.VISIBLE
            binding.topBar.visibility = View.VISIBLE
            binding.opButtons.visibility = View.VISIBLE
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            isLandscape = false
        } else {
            binding.bottomLayout.visibility = View.GONE
            binding.topBar.visibility = View.GONE
            binding.opButtons.visibility = View.GONE
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            isLandscape = true
            binding.playerContainer1.postDelayed({
                Tips.show("使用物理返回键退出全屏")
            }, 1000)
        }

        binding.playerContainer1.post {
            deviceMediaRender_1.resize()
            deviceMediaRender_2.resize()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        deviceFacade.disconnect()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean =
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (isLandscape) {
                switchFullScreen()
                true
            }
            else {
                finish()
                true
            }
        } else super.onKeyDown(keyCode, event)

    fun trsformEventName(eventType: Int): String {
        return when (eventType) {
            DeviceStoragePlayback.Index.EVENT_MOTION_DETECTED -> "有人移动"
            DeviceStoragePlayback.Index.EVENT_HUMAN_BODY -> "发现人形"
            DeviceStoragePlayback.Index.EVENT_SOUND -> "发现声音"
            else -> "未知事件"
        }
    }


    inner class ListAdapter : RecyclerView.Adapter<ViewHolder>() {
        private val apList: MutableList<DeviceStoragePlayback.Index> = java.util.ArrayList()
        fun refresh(list: List<DeviceStoragePlayback.Index>) {
            apList.clear()
            apList.addAll(list)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
            val view: View = LayoutInflater.from(viewGroup.context)
                .inflate(R.layout.item_cloud_record_list, viewGroup, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
            val item = apList[position]
            if (item.event > 0) {
                viewHolder.start.text = "${DateUtil.getStrToTime(item.start)} --  ${trsformEventName(item.event)}"
            } else {
                viewHolder.start.text = "${DateUtil.getStrToTime(item.start)}"
            }

            viewHolder.itemView.setOnClickListener { view: View? ->
                Toast.makeText(this@ThreeChannelDevicePlaybackActivity, "切换到：${DateUtil.getStrToTime(item.start)}，请稍候...", Toast.LENGTH_LONG).show()
                deviceStorageMediaSource.seek(item.start)
                deviceMediaRender_1.reset()
                deviceMediaRender_2.reset()
            }
        }

        override fun getItemCount(): Int {
            return apList.size
        }
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val start: TextView

        init {
            start = view.findViewById(R.id.start)
        }
    }
}